package com.example.computer_exam_training_sys.controller;

import com.example.computer_exam_training_sys.dto.PracticeSummaryDTO;
import com.example.computer_exam_training_sys.entity.UserPractice;
import com.example.computer_exam_training_sys.service.UserPracticeService;
import com.example.computer_exam_training_sys.vo.PracticeStatisticsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/userPractices")
@CrossOrigin
public class UserPracticeController {

    @Autowired
    private UserPracticeService service;

    // 查询所有
    @GetMapping("/all")
    public List<UserPractice> getAllPractices() {
        return service.selectAll();
    }

    // 查询某用户的练习记录
    @GetMapping("/user/{userId}")
    public List<UserPractice> getByUserId(@PathVariable Integer userId) {
        return service.selectByUserId(userId);
    }

    // 查询某用户的练习记录（带课程、知识点信息）
    @GetMapping("/user-vo/{userId}")
    public List<com.example.computer_exam_training_sys.vo.UserPracticeCourseVO> getPracticeCourseByUserId(@PathVariable Integer userId) {
        return service.selectPracticeCourseByUserId(userId);
    }

    // 查询所有用户练习记录（带课程、知识点信息）
    @GetMapping("/all-vo")
    public List<com.example.computer_exam_training_sys.vo.UserPracticeCourseVO> getAllPracticeCourse() {
        return service.selectAllPracticeCourse();
    }

    @PostMapping("/add")
    public int addPractice(@RequestBody UserPractice practice) {
        service.insert(practice);
        return practice.getPracticeId(); // 返回主键
    }

    // 练习统计：练习次数 + 正确率
    @GetMapping("/statistics")
    public PracticeStatisticsVO getPracticeStats(@RequestParam int userId, @RequestParam int pointId) {
        return service.getPracticeStatisticsByUserAndPoint(userId, pointId);
    }

    // 练习次数和正确率汇总接口（DTO）
    @GetMapping("/summary")
    public PracticeSummaryDTO getPracticeSummary(@RequestParam Integer userId, @RequestParam Integer pointId) {
        return service.getPracticeSummary(userId, pointId);
    }
    @GetMapping("/point-progress")
    public Map<String, Object> getPointProgress(
            @RequestParam Integer userId,
            @RequestParam Integer courseId) {

        int practiced = service.countDistinctPoints(userId, courseId); // 用户练习过的知识点数（去重）
        int total = service.countPointsByCourse(courseId);             // 当前课程下的总知识点数

        double progress = total == 0 ? 0.0 : (practiced * 100.0 / total);

        Map<String, Object> result = new HashMap<>();
        result.put("practicedCount", practiced);
        result.put("totalCount", total);
        result.put("progress", progress); // 进度百分比

        return result;
    }

}